# Path: im-backend-master/app/api/conversation.py

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from ..schemas.conversation import APIResponse, CreateConversationRequest
from ..db.session import get_db
from ..db.models.user import User
from ..utils.security import get_current_user
from ..services.conversation import ConversationService

# 初始化路由
router = APIRouter(prefix="/conversation", tags=["会话管理"])

@router.get("/list", summary="获取会话列表")
async def get_conversation_list(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的会话列表"""
    try:
        conversations = ConversationService.get_conversations(db, current_user.id)
        return {
            "code": 0,
            "message": "成功！",
            "data": conversations  # 直接返回会话列表，不包装在额外的对象中
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail={"message": f"获取会话列表失败: {str(e)}"})

@router.post("/create", summary="创建新会话")
async def create_conversation(
    request: CreateConversationRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的会话"""
    try:
        conversation = ConversationService.create_or_get_conversation(
            db, 
            current_user.id, 
            request.userId
        )
        return {
            "code": 0,
            "message": "成功！",
            "data": conversation
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail={"message": str(e)})
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail={"message": f"创建会话失败: {str(e)}"})